<?php


namespace App\Http\Service;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Request;

class WordService
{
    private ?Client $client = null;

    public function __construct()
    {
        $this->client = new Client(['base_uri' => 'https://qyapi.weixin.qq.com', 'verify' => false]);
    }

    public function build($content)
    {
        return json_decode($content, true);
    }

    public function getAccessToken($secret)
    {
        $data = $this->client->get(sprintf("/cgi-bin/gettoken?corpid=%s&corpsecret=%s", env('WORDK_CORP_ID'), $secret));
        $res = $this->build($data->getBody()->getContents());
        if ($res['errmsg'] != "ok") {
            throw new \Exception($res['errmsg']);
        }

        return $res['access_token'];
    }

    /**
     * 消息发送
     * @param $workId
     * @param $out_trade_no
     * @param $bid
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendMessage($workId,$out_trade_no,$bid){
        $http=Request::root().'/v1/business/show/'.$bid;
        $data = $this->client->post(sprintf("/cgi-bin/message/send?access_token=%s", $this->getAccessToken(env('WORDK_APP_SECRET'))),[
                'json'=>[
                    'touser'=>$workId,
                    'msgtype'=>'text',
                    'agentid'=>env('WORDK_APP_AGENTID'),
                    "text" => [
                            "content" => "您有一条新的喂养订单\n 订单号：{$out_trade_no} \n 详细信息可查看<a href=\"{$http}\">喂养详情</a>。"
                    ],
                ]
        ]);
        $res = $this->build($data->getBody()->getContents());
        if ($res['errmsg'] != "ok") {
            return $res['errmsg'];
        }
        return  $res;
    }






}
